package cn.edu.nju.software.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.sql.DataSource;

import cn.edu.nju.software.bean.storage.Admin;
import cn.edu.nju.software.dao.intf.AdminDao;

public class AdminDaoImpl implements AdminDao {
	private DataSource ds = null;

	public AdminDaoImpl() {
		try {
			ds = JDBCUtil.getDataSource();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Admin login(String signInName, String password) throws SQLException {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Admin admin = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			pstmt = con
					.prepareStatement("SELECT name FROM admin "
							+ "WHERE act_name = ? AND password = ?");
			pstmt.setString(1, signInName);
			pstmt.setString(2, password);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				admin = new Admin(signInName, rs.getString(1), password);
			}
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			con.rollback();
			throw e;
		} finally {
			JDBCUtil.closeResultSet(rs);
			JDBCUtil.closeStatement(pstmt);
			JDBCUtil.closeConnection(con);
		}
		return admin;
	}

	@Override
	public void updateAdmin(Admin admin) throws SQLException {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = ds.getConnection();
			con.setAutoCommit(false);
			pstmt = con.prepareStatement("UPDATE admin SET name = ?, password = ? WHERE act_name = ?");
			pstmt.setString(1, admin.getName());
			pstmt.setString(2, admin.getPassword());
			pstmt.setString(3, admin.getSignInName());
			pstmt.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			con.rollback();
			throw e;
		} finally {
			JDBCUtil.closeStatement(pstmt);
			JDBCUtil.closeConnection(con);
		}
	}
}
